<?php

namespace controller;

/**
 * Description of Contact
 *
 * @author Damian
 */
class Contact extends Shop {

    public function __construct($options = array()) {
        parent::__construct($options);
        if (!$this->Customer) {
            $this->redirect($this->shop->URL);
        }
    }

    public function newConversation() {
        
    }

    public function index() {
        $layoutView = $this->getLayoutView();
        $layoutView->set("paneltitle", "Skontaktuj się ze sprzedawcą");
        $conversationsCriteria = new \model\Criteria();
        $conversationsCriteria->from(\model\TblConversation::getModel()->getTable())
                ->where(\model\TblConversation::CUSTOMER_ID, "=", $this->Customer->CustomerID);
        $Conversations = \model\TblConversation::getModel()->all($conversationsCriteria);
        $view = $this->getActionView();
        if ($Conversations){
            $maxID=0;
            $conversationsCount=0;
            $view->set("conversations",$Conversations);
            $messagesConv=array();
            $unreadConv = array();
            $session = \library\Registry::get("session");
            $customer = $session->get("customer");
            foreach ($Conversations as $conv){
                $conversationsCount++;
                $messageCriteria = new \model\Criteria();
                $messageCriteria->from(\model\TblAnswer::getModel()->getTable())
                        ->where(\model\TblAnswer::CONVERSATION_ID, "=",$conv->ConversationID)
                        ->order(\model\TblAnswer::ADDITION_DATE,"Asc");
                if ($customer){
                    $messageCriteria->limit($customer->MessagesHitory);
                }
                $messageCountCriteria = new \model\Criteria();
                $messageCountCriteria->from(\model\TblAnswer::getModel()->getTable())
                        ->where(\model\TblAnswer::CONVERSATION_ID, "=",$conv->ConversationID)
                        ->where(\model\TblAnswer::SEND_BY_CUSTOMER,"=",0,false, " and ")
                        ->where(\model\TblAnswer::SEEN,"=",0,false, " and ");
                $messages = \model\TblAnswer::getModel()->all($messageCriteria);
                $messagesConv[$conv->ConversationID]=$messages;
                $unreadConv[$conv->ConversationID]=$messageCountCriteria->count();
                if ($messages[sizeof($messages)-1]->AnswerID>$maxID){
                    $maxID=$messages[sizeof($messages)-1]->AnswerID;
                }
            }
            $view->set("unreadConv",$unreadConv);
            $view->set("maxID",$maxID);
            $view->set("coversationsCount",$conversationsCount);
            $view->set("messages",$messagesConv);
        }
        $this->render();
    }

    public function server() {

    }

    public function client() {
       
    }

}
